package br.mg.bhe.ftpobre.fs.data.xml;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import br.mg.bhe.ftpobre.ConnectionData;
import br.mg.bhe.ftpobre.util.XmlUtil;

/**
 * 
 * @author Aureliano
 */
public class ConnectionDataParser implements IDocumentParser<ConnectionData> {

	@Override
	public Document parse(ConnectionData data) {
		Document doc;
		try {
			doc = XmlUtil.createEmptyDocument();
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		
		List<Element> nodes = createDocumentNodes(doc, data);
		Element root = doc.createElement("connection");
		
		
		for (Element e : nodes) {
			root.appendChild(e);
		}
		
		doc.appendChild(root);
		return doc;
	}

	@Override
	public ConnectionData parse(Document doc) {
		ConnectionData c = new ConnectionData();
		NodeList nodes = doc.getFirstChild().getChildNodes();
		
		c.setHost(nodes.item(1).getTextContent());
		c.setPort(Integer.parseInt(nodes.item(3).getTextContent()));
		c.setUser(nodes.item(5).getTextContent());
		c.setPassword(nodes.item(7).getTextContent());
		c.setWorkingOnline(Boolean.parseBoolean(nodes.item(9).getTextContent()));
		
		return c;
	}

	private List<Element> createDocumentNodes(Document doc, ConnectionData c) {
		List<Element> nodes = new ArrayList<Element>();
		
		Element child = doc.createElement("host");
		child.setTextContent(c.getHost());
		nodes.add(child);
		
		child = doc.createElement("port");
		child.setTextContent(String.valueOf(c.getPort()));
		nodes.add(child);
		
		child = doc.createElement("user");
		child.setTextContent(c.getUser());
		nodes.add(child);
		
		child = doc.createElement("password");
		child.setTextContent(c.getPassword());
		nodes.add(child);
		
		child = doc.createElement("workingOnline");
		child.setTextContent(String.valueOf(c.isWorkingOnline()));
		nodes.add(child);
		
		return nodes;
	}
}